import React from 'react';
import { Modal, Button, message, Form, Input, DatePicker } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { add } from '@/services/CheckBook';
import moment from 'moment';

class AddModal extends React.Component {

  constructor(props) {
    super(props);
    this.formRef = React.createRef()
    this.state = {
      isShowModal: false,
      isLoading: false
    };
  }

  onShowModal = () => {
    this.setState({ isShowModal: true })
  }

  onCancel = () => {
    this.setState({ isShowModal: false })
  }

  /* 提交数据 */
  onConfirm = async () => {
    try {
      const { add: addSuccessCallback, id } = this.props;
      const { validateFields } = this.formRef.current;
      const values = await validateFields();
      if (values.date) {
        values.startDate = moment(values.date[0]).format('YYYY-MM-DD 00:00:00');
        values.endDate = moment(values.date[1]).format('YYYY-MM-DD 59:59:59');
        delete values.date;
      }
      const params = { ...values, benefitUnitId: id }
      this.setState({ isLoading: true })
      await add(params);
      addSuccessCallback ? addSuccessCallback() : null;
      message.success('添加成功！');
      this.setState({ isShowModal: false });
    } catch (e) {
      console.error('新增学校：', e);
    } finally {
      this.setState({ isLoading: false })
    }
  }

  render() {
    const { isShowModal, isLoading } = this.state;
    const children = this.props.children;
    const { formRef, onCancel, onConfirm } = this
    return (
      <React.Fragment>
        <Button type="link" onClick={this.onShowModal} icon={<PlusOutlined />}>{children}</Button>
        <Modal
          title="新增图书清查任务"
          okText="新增"
          width="50vw"
          confirmLoading={isLoading}
          visible={isShowModal}
          onCancel={onCancel}
          onOk={onConfirm}>
          <Form
            ref={formRef}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 16 }}
            layout="horizontal">
            <Form.Item
              name='name'
              label='清查任务名称：'
              rules={[{ required: true, message: '清查任务名称不能为空' }]}>
              <Input placeholder='请输入清查任务名称' />
            </Form.Item>
            <Form.Item
              name='date'
              label='选择起止日期：'
              rules={[{ required: true, message: '选择起止日期不能为空' }]}>
              <DatePicker.RangePicker allowClear style={{width: '100%'}} />
            </Form.Item>
            <Form.Item
              name='remark'
              label='备注：'>
              <Input.TextArea placeholder='请输入备注' />
            </Form.Item>
          </Form>
        </Modal>
      </React.Fragment>
    );
  }
};

export default AddModal
